<?php
/**
 * @ClassName: SplitAccountLogic
 * @Description: 分账服务
 * @author: gydtrade
 * @Date: 2025-09-26 15:51
 * @Version: V1.0.0
 */

namespace app\common\rebate;

use app\common\enum\MerchantEnum;
use app\common\enum\OrderStatus;
use app\common\enum\PayStatus;
use app\common\enum\RebateEnum;
use app\common\enum\ShopGoodsEnum;
use app\common\model;
use think\Db;
use think\facade\Log;

class SplitAccountLogic extends HandleLogic
{
    public function doRebate($order_sn)
    {
        makelog("——开始分账——" . date('Y-m-d H:i:s'), 'order/split-account');
        makelog("分账订单号：" . $order_sn, 'order/split-account');

        //获取订单信息
        $this->getOrderByOrderSn($order_sn);

        if (!$this->order_sn || !$this->orderInfo) {
            makelog($this->order_sn . '订单不存在', 'order/split-account');
            return json(['code' => 0, 'msg' => '订单不存在']);
        }

        if ($this->orderInfo['pay_status'] != PayStatus::pay) {
            makelog($this->order_sn . '订单未支付，不能分成，付款状态：' . $this->orderInfo['pay_status'], 'order/split-account');
            return json(['code' => 0, 'msg' => '订单未支付，不能分成']);
        }

        if (!in_array($this->orderInfo['order_status'], [OrderStatus::WAITCCOMMENT, OrderStatus::FINISH])) {
            makelog($this->order_sn . '订单未收货，不能分成，订单状态：' . $this->orderInfo['order_status'], 'order/split-account');
            return json(['code' => 0, 'msg' => '订单未收货，不能分成']);
        }

        $res = $this->getBuyer($this->orderInfo);
        if ($res['code'] == 0) {
            makelog($this->orderInfo['member_id'] . '：' . $res['msg'], 'order/split-account');
            return json($res);
        }
        $buyMember = $res['data'];
        makelog("下单购买人：" . $buyMember['id'] . '#' . $buyMember['nickname'], 'order/split-account');

        //查询分成配置信息
        $divideConfig = model\ShopOrderGoods::alias('og')
            ->join('shop_goods g', 'g.id = og.goods_id')
            ->join('rebate_config rc', 'rc.id=g.rc_id')
            ->join('shop_order o', 'o.id=og.order_id')
            ->where([
                'og.order_id' => $this->orderInfo['id'],
                'g.is_divide' => ShopGoodsEnum::is_divide_yes,
                'og.divide_status' => ShopGoodsEnum::divide_no
            ])
            ->field('rc.*,o.order_amount,g.store_id,g.is_divide,' .
                'og.id as order_goods_id,og.order_id,og.goods_id,og.sale_price,og.member_price,og.cost_price,og.premium_price,og.goods_num,og.total_num,og.spec_key' .
                'og.commission,og.income_company,og.income_attract,og.income_market,og.free_queuing_ratio,og.income_operation,og.income_other,og.divide_status')
            ->select();
        makelog("分成配置信息\n" . json_encode($divideConfig, 320), 'order/split-account');

        if (!$divideConfig || count($divideConfig) <= 0) {
            makelog($order_sn . '：订单不支持分成/没有配置分成模式/已分账', 'order/split-account');
            return json(['code' => 0, 'msg' => '订单不支持分成/没有配置分成模式/已分账']);
        }

        //分成开关
        $split_switch = true;

        foreach ($divideConfig as $tag) {
            $tag['buyMember'] = $buyMember;
            $tag['orderInfo'] = $this->orderInfo;

            if ($tag['is_divide'] == ShopGoodsEnum::is_divide_no) {
                makelog($tag['goods_id'] . '：商品设置不分账，无法分成', 'order/split-account');
                continue;
            }

            $storeUser = model\Store::alias('s')
                ->join('member m', 'm.id=s.member_id')
                ->field('s.user_type,m.id,m.nickname,m.agent_level')
                ->where(['s.id' => $tag['store_id']])
                ->find();
            makelog("店铺管理员信息\n" . json_encode($storeUser, 320), 'order/split-account');
            if (!$storeUser) {
                makelog($tag['store_id'] . '：店铺不存在，无法分成', 'order/split-account');
                continue;
            }

            if ($storeUser['user_type'] != MerchantEnum::shop || $storeUser['user_type'] != MerchantEnum::water) {
                //类型异常,门店不是联盟商家，也不是水站
                makelog($storeUser['user_type'] . '：无分成模式，无法分成', 'order/split-account');
                continue;
            }
            $tag['storeUser'] = $storeUser;

            //分账比例
            $company_ratio = $tag['income_company'];//公司运营收益
            $attract_ratio = $tag['income_attract'];//招商收益
            $market_ratio = $tag['income_market'];//市场收益
            $free_queuing_ratio = $tag['free_queuing_ratio'];//排队免单分成比例
            $operation_ratio = $tag['income_operation'];//运营中心收益
            $other_ratio = $tag['income_other'];//其他收益（溢价+剩余）

            //利润来源([商品实际售价-溢价-成本价]和商品佣金)
            if ($tag['commission_from'] == RebateEnum::commission_from_sale) {
                //商家收益(成本价)
                $income_store = $tag['cost_price'] * $tag['goods_num'];
                //利润=商品实际售价-溢价-成本价
                $money = $tag['member_price'] - $tag['premium_price'] - $income_store;
                makelog('销售价：' . $tag['member_price'], 'order/split-account');
                makelog('成本价：' . $income_store, 'order/split-account');
                makelog('购买套餐数量：' . $tag['goods_num'], 'order/split-account');
                makelog('购买总数量：' . $tag['total_num'], 'order/split-account');
            } else {
                //商品佣金
                $money = $tag['commission'] * $tag['goods_num'];
                //商家收益(成本价)
                $income_store = $tag['member_price'] - $money;
                makelog('销售价：' . $tag['member_price'], 'order/split-account');
                makelog('商品佣金：' . $tag['commission'], 'order/split-account');
                makelog('成本价：' . $income_store, 'order/split-account');
                makelog('购买套餐数量：' . $tag['goods_num'], 'order/split-account');
                makelog('购买总数量：' . $tag['total_num'], 'order/split-account');
            }

            if ($money <= 0) {
                makelog($money . '：利润/佣金小于等于0，无法分成', 'order/split-account');
                continue;
            }
            //溢价
            $premium_price = $tag['premium_price'] * $tag['goods_num'];
            makelog('利润：' . $money, 'order/split-account');
            makelog('溢价：' . $premium_price, 'order/split-account');

            //商家收益(成本价)
            $this->incomeStore($tag, $income_store, $split_switch);
            makelog("商家收益：" . $income_store, 'order/split-account');

            //平台收益=平台收益比例*分账金额
            $income_company = floatval($company_ratio / 100 * $money);
            $this->incomeCompany($tag, $income_company, '平台收益', $split_switch);
            makelog("平台收益：" . $income_company, 'order/split-account');

            //招商收益=招商收益比例*分账金额
            $income_attract = floatval($attract_ratio / 100 * $money);
            $attractData = $this->attractRangeRebate($tag, $income_attract, $split_switch);
            makelog("招商极差收益：" . json_encode($attractData), 'order/split-account');
        }
    }

    /**
     * 商家收益(成本价)
     * @param $params
     * @param $income_store
     * @param $split_switch
     * @return void
     */
    function incomeStore($params, $income_store, $split_switch)
    {
        $rebateFlag = RebateEnum::divide_type_store_cost;
        if (!data_get($params, 'buyMember', '') ||
            !data_get($params, 'orderInfo', '') ||
            !data_get($params, 'storeUser', '')
        ) {
            makelog($rebateFlag . '没有配置 buyMember，orderInfo，storeUser', 'order/split-account');
            return;
        }
        if ($split_switch) {
            $this->createRebateLog([
                'profitUser' => $params['storeUser'],
                'buyMember' => $params['buyMember'],
                'orderInfo' => $params['orderInfo'],
                'paramData' => [],
                'tag' => $rebateFlag,
                'money' => $income_store,
                'remark' => '商家成本',
                'separate_store_id' => $params['store_id'],//分账商家
            ]);
        }
    }

    /**
     * 平台收益
     * @param $params
     * @param $income_company
     * @param $flag
     * @param $split_switch
     * @return void
     */
    function incomeCompany($params, $income_company, $flag, $split_switch)
    {
        $rebateFlag = RebateEnum::divide_type_company_award;
        if ($income_company <= 0) {
            makelog($rebateFlag . '分账金额小于0,分账失败' . $income_company, 'order/split-account');
            return;
        }
        if (!data_get($params, 'buyMember', '')
            || !data_get($params, 'orderInfo', '')
        ) {
            makelog($rebateFlag . '没有配置，buyMember，orderInfo，storeUser', 'order/split-account');
            return;
        }
        $companyMember = model\Member::where(['id' => env('company_income_uid')])->find();
        if (!$companyMember) {
            makelog($rebateFlag . '没有配置平台收益会员', 'order/split-account');
            return;
        }
        if ($split_switch) {
            $this->createRebateLog([
                'profitUser' => $companyMember,
                'buyMember' => $params['buyMember'],
                'orderInfo' => $params['orderInfo'],
                'params' => [],
                'tag' => $rebateFlag,
                'money' => $income_company,
                'remark' => '平台收益-' . $flag,
                'separate_member_id' => $companyMember['id'],//分账会员
            ]);
        }
    }

    /**
     * 生成分成日志
     * @param $params
     * @return void
     */
    protected function createRebateLog($params)
    {
        $profitUser = data_get($params, 'profitUser');//分成用户
        $buyMember = data_get($params, 'buyMember');//消费用户
        $orderInfo = data_get($params, 'orderInfo');//订单信息
        $paramData = data_get($params, 'paramData');//其它参数
        $tag = data_get($params, 'tag', '');//分成标识
        $money = data_get($params, 'money');//分成金额
        if (!$profitUser || !$buyMember || !$orderInfo || !$paramData || !$tag || !$money) {
            makelog($tag . '生成分成日志参数异常', 'order/split-account');
            return;
        }
        Db::startTrans();
        try {
            $rebateLogId = model\RebateLog::insertGetId([
                'profit_member_id' => $profitUser['id'],
                'profit_nickname' => $profitUser['nickname'],
                'buy_member_id' => data_get($buyMember, 'id', ''),
                'buy_nickname' => data_get($buyMember, 'nickname', ''),
                'order_sn' => data_get($orderInfo, 'order_sn', ''),
                'order_id' => data_get($orderInfo, 'id', ''),
                'store_id' => data_get($orderInfo, 'store_id', 0),
                'goods_price' => data_get($orderInfo, 'order_amount', 0),
                'commission' => $money,
                'points' => data_get($paramData, 'points', 0),//获得积分
                'profit_level' => data_get($profitUser, 'agent_level', ''),//获佣用户级别
                'member_level' => data_get($buyMember, 'agent_level', ''),//购买人级别
                'status' => RebateLogEnum::status_stay,
                'type' => data_get($params, 'type', 0),//分成类型：0默认，1商城，2付呗，3微唯宝订单
                'remark' => data_get($params, 'remark', ''),//备注
                'create_time' => date("Y-m-d H:i:s"),
                'update_time' => date("Y-m-d H:i:s"),
                'marketing_id' => data_get($params, 'marketing_id', 0),//营销活动ID
                'enable' => 1,// 生效: 失效的情况，订单收货不会到账
                'tag' => $tag,
            ]);
            if ($rebateLogId) {
                Db::commit();
                Log::info($tag . '分成执行成功');
            } else {
                Db::rollBack();
                Log::error($tag . '分成执行失败，数据回滚');
            }

        } catch (\Exception $e) {
            Log::error($tag . '生成分成日志异常，line:' . $e->getLine() . '-' . $e->getMessage());
            Db::rollBack();
        }
    }

}